#define _CRT_SECURE_NO_WARNINGS 1

#include "List.h"

LTNode* BuyNewNode(LTDatatype x)
{
	LTNode* node = (LTNode*)malloc(sizeof(LTNode));
	if (node == NULL)
	{
		perror("malloc fail\n");
		return;
	}

	node->next = NULL;
	node->prev = NULL;
	node->data = x;

	return node;
}

LTNode* LTInit()
{
	LTNode* phead = BuyNewNode(-1);
	phead->next = phead;
	phead->prev = phead;

	return phead;
}

void LTDestroy(LTNode* phead)
{
	assert(phead);

	LTNode* cur = phead->next;
	while(cur != phead)
	{
		LTNode* next = cur->next;
		free(cur);
		cur = next;
	}

	//释放哨兵节点
	free(phead);
}

void LTPrint(LTNode* phead)
{
	assert(phead);

	LTNode* cur = phead->next;
	printf("<=>head<=>");
	while (cur != phead)
	{
		printf("%d<=>", cur->data);
		cur = cur->next;
	}
	printf("\n");
}

void LTPushBack(LTNode* phead, LTDatatype x)
{
	assert(phead);

	//定义一个新节点
	LTNode* newnode = BuyNewNode(x);
	
	//找尾
	LTNode* tail = phead->prev;

	//尾插
	tail->next = newnode;
	newnode->prev = tail;
	phead->prev = newnode;
	newnode->next = phead;

	//SLInsert(phead, x);
}

bool LTEmpty(LTNode* phead)
{
	return phead->next == phead;
}

void LTPopBack(LTNode* phead)
{
	assert(phead);
	assert(!LTEmpty(phead));

	LTNode* tail = phead->prev;
	LTNode* tailPrev = tail->prev;

	phead->prev = tailPrev;
	tailPrev->next = phead;

	free(tail);
	tail = NULL;

	//SLErase(phead->prev);

}

void LTPushFront(LTNode* phead, LTDatatype x)
{
	assert(phead);

	LTNode* newnode = BuyNewNode(x);
	LTNode* first = phead->next;

	newnode->next = first;
	first->prev = newnode;
	phead->next = newnode;
	newnode->prev = phead;

	//SLInsert(phead->next, x);

}

void LTPopFront(LTNode* phead)
{
	assert(phead);
	assert(!LTEmpty(phead));

	LTNode* first = phead->next;
	LTNode* next = first->next;

	phead->next = next;
	next->prev = phead;

	free(first);
	first = NULL;

	//SLErase(phead->next);

}

LTNode* LTFind(LTNode* phead, LTDatatype x)
{
	assert(phead);

	LTNode* cur = phead->next;
	while (cur != phead)
	{
		if (cur->data == x)
		{
			return cur;
		}
		cur = cur->next;
	}

	return NULL;
}

void LTInsert(LTNode* pos, LTDatatype x)
{
	assert(pos);

	LTNode* newnode = BuyNewNode(x);
	LTNode* posPrev = pos->prev;

	newnode->prev = posPrev;
	posPrev->next = newnode;
	newnode->next = pos;
	pos->prev = newnode;
}

void LTErase(LTNode* pos)
{
	assert(pos);

	LTNode* n = pos->next;
	LTNode* p = pos->prev;

	p->next = n;
	n->prev = p;

	free(pos);
	pos = NULL;
}
